//
//  ForumDetailController.m
//  myCar
//
//  Created by 刘莉 on 14-11-7.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "ForumDetailController.h"
#import "Forum.h"
#import "ForumCell.h"
#import "MJRefresh.h"
#import "WebController.h"
#import "WebColor.h"
#import "AFNetworking.h"
#import "DataBaseHandler.h"
#import "MBProgressHUD.h"
@interface ForumDetailController ()<UITableViewDataSource, UITableViewDelegate, UIAlertViewDelegate>

@property (nonatomic, retain) NSMutableArray *forumArr;
@property (nonatomic, retain) UITableView *table;
@property (nonatomic, assign) NSInteger countX;




@end

@implementation ForumDetailController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.forumArr = [NSMutableArray array];
        
    }
    return self;
}
- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBar.hidden = NO;
    self.tabBarController.tabBar.hidden = NO;
    DataBaseHandler *handler = [DataBaseHandler shareInstance];
    [handler createCollectionTable];
}
- (void)setBase:(Base *)base
{
    if (_base != base) {
        [_base release];
        _base = [base retain];
    }
    [self startConnection];
}

- (void)startConnection
{
    MBProgressHUD *hub = [[MBProgressHUD alloc] initWithView:self.view];
    [hub setMode:MBProgressHUDModeIndeterminate];
    [self.view addSubview:hub];
    [hub show:YES];
    NSString *str = [NSString stringWithFormat:@"http://mrobot.pcauto.com.cn/v3/bbs/newForums/%@?pageNo=1&pageSize=19&orderby=replyat" , self.base.idNum];
    
    AFHTTPRequestOperationManager *manager1 = [AFHTTPRequestOperationManager manager];
    
    [manager1.responseSerializer setAcceptableContentTypes: [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css", nil]];
    
    [manager1 GET:str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSArray *arr = [responseObject objectForKey:@"topicList"];
        for (NSDictionary *dic in arr) {
            Forum *forum = [[Forum alloc]initWithDictionary:dic];
            [self.forumArr addObject:forum];
            [forum release];
        }
        [self.table reloadData];
        [hub removeFromSuperview];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(50, 120, 280, 100)];
        imageView.image = [UIImage imageNamed:@"poNet.jpg"];
        self.table.backgroundView = imageView;
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"对不起暂无网络" message:@"请返回" delegate:self cancelButtonTitle:@"返回" otherButtonTitles:@"确定", nil];
        [alertView show];
        [alertView release];
        [imageView release];
    }];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    // Do any additional setup after loading the view.
    [self initView];
    [self setupRefresh];
    [self openHandler];   
}

- (void)openHandler
{
    DataBaseHandler *handler = [DataBaseHandler shareInstance];
    //[handler openDB];
    [handler createCollectionTable];
    
    NSArray *collectArr = [handler selectCollectionAll];
    int flag = 1;
    for (Base *basem in collectArr) {
        if ([basem.name isEqualToString:[NSString stringWithFormat:@"%@",self.base.name]]) {
            self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"collect2.png"] style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonItem:)];
            flag = 0;
        }
    }
    if (1 == flag) {
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"collect1.png"] style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonItem:)];
    }
}

- (void)initView
{
    self.table = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 64) style:(UITableViewStylePlain)];
    self.table.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.table.delegate = self;
    self.table.dataSource = self;
    [self.table registerClass:[ForumCell class] forCellReuseIdentifier:@"forum"];
    [self.view addSubview:self.table];
    [_table release];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.forumArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ForumCell *cell = [tableView dequeueReusableCellWithIdentifier:@"forum"];
    Forum *forum = self.forumArr[indexPath.row];
    cell.titLabel.text = forum.title;
    cell.nameLabel.text = forum.nickName;
    NSString *str = forum.flag;
    cell.flagLabel.layer.borderColor = [UIColor clearColor].CGColor;
    if ([str isEqualToString:@"nil"]) {
        cell.flagLabel.text = nil;
    } else {
        if ([str isEqualToString:@"精"]) {
            cell.flagLabel.layer.borderColor = [UIColor redColor].CGColor;
            cell.flagLabel.textColor = [UIColor redColor];
        } else {
            cell.flagLabel.layer.borderColor = [UIColor blueColor].CGColor;
            cell.flagLabel.textColor = [UIColor blueColor];
        }
        cell.flagLabel.layer.borderWidth = 1;
        cell.flagLabel.text = str;
    }
    cell.replyLabel.text = [NSString stringWithFormat:@"%@阅/%@", forum.view, forum.replyCount];
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 50)];
    imageView.image = [UIImage imageNamed:@"cellbg.jpg"];
    cell.backgroundView = imageView;
    [imageView release];
    return cell;
    
}



- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)setupRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [self.table addHeaderWithTarget:self action:@selector(headerRereshing)];
    [self.table headerBeginRefreshing];
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [self.table addFooterWithTarget:self action:@selector(footerRereshing)];
    [self.table footerEndRefreshing];
    //
    // 设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
    self.table.headerPullToRefreshText = @"下拉刷新...";
    self.table.headerReleaseToRefreshText = @"松开即可刷新...";
    self.table.headerRefreshingText = @"刷新中...";
    
    self.table.footerPullToRefreshText = @"上拉可以加载更多数据";
    self.table.footerReleaseToRefreshText = @"松开马上加载更多数据";
    self.table.footerRefreshingText = @"加载中";
    
    self.countX = 2;
    NSLog(@"se.countX %d", self.countX);
}

//- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
//{
//    if (buttonIndex == 0) {
//        [self.navigationController popViewControllerAnimated:YES];
//    }
//}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    Forum *forum = self.forumArr[indexPath.row];
    WebController *webVC = [[WebController alloc]init];
    webVC.forum = forum;
   
    [self.navigationController pushViewController:webVC animated:YES];
    [webVC release];
    
    
}

- (void)rightBarButtonItem:(UIBarButtonItem *)button
{
    DataBaseHandler *handler = [DataBaseHandler shareInstance];
    if ([button.image isEqual:[UIImage imageNamed:@"collect1.png"]]) {
        [handler insertCollection:self.base];
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"收藏成功" delegate:self cancelButtonTitle:@"请返回" otherButtonTitles:nil, nil];
        [alertView show];
        button.image = [UIImage imageNamed:@"collect2.png"];
    } else {
        button.image =[UIImage imageNamed:@"collect1.png"];
        [handler deleteCollection:self.base];
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"删除成功" delegate:self cancelButtonTitle:@"请返回" otherButtonTitles:nil, nil];
        [alertView show];
    }
    
   
}





#pragma mark 开始进入刷新状态
- (void)headerRereshing
{
    // 2.2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        // 刷新表格
        [self.table reloadData];
        
        [self.table reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.table headerEndRefreshing];
    });
}

- (void)footerRereshing
{

    NSString *str = [NSString stringWithFormat:@"http://mrobot.pcauto.com.cn/v3/bbs/newForums/%@?pageNo=%d&pageSize=19&orderby=replyat", self.base.idNum, self.countX];
    
    AFHTTPRequestOperationManager *manager1 = [AFHTTPRequestOperationManager manager];
    
    [manager1.responseSerializer setAcceptableContentTypes: [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css", nil]];
    
    [manager1 GET:str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSMutableArray *arr = [responseObject objectForKey:@"topicList"];
        for (NSDictionary *dic in arr) {
            Forum *forum = [[Forum alloc]initWithDictionary:dic];
            [self.forumArr addObject:forum];
            [forum release];
            [self.table reloadData];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
    
    // 2.2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [self.table reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.table footerEndRefreshing];
        self.countX += 1;
        NSLog(@"self.countX %d", self.countX);
    });
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
